package com.shanghaionstar.nav;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewAnimator;

import com.onstar.cn.SharedPoiItemInfo;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.Constants;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.mag.poi.FavoriteEntity;
import com.onstar.cn.map.common.LocationType;
import com.onstar.cn.map.common.PoiItemInfo;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.sqlite.entities.PoiSearchHistory;
import com.onstar.cn.weight.CustomBtnDrawableRightCenter;
import com.onstar.cn.weight.CustomImageView;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.activity.VehicleLoadingActivity;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.iview.ILoginAndOutListener;
import com.shanghaionstar.iview.ILoginListener;
import com.shanghaionstar.nav.adapter.NavPoiSearchFavAdapter;
import com.shanghaionstar.nav.adapter.NavPoiSearchHistoryAdapter;
import com.shanghaionstar.nav.adapter.NavPoiSearchListAdapter;
import com.shanghaionstar.nav.adapter.NavSearchItemGridViewAdapter;
import com.shanghaionstar.nav.iview.INavMainView;
import com.shanghaionstar.nav.model.MapChoosePoiType;
import com.shanghaionstar.nav.model.NavInfoModel;
import com.shanghaionstar.nav.model.SetAddressResult;
import com.shanghaionstar.nav.presenter.NavMainPresenter;
import com.shanghaionstar.nav.service.AbstractMapActivity;
import com.shanghaionstar.pin.model.PinModel;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;
import com.shanghaionstar.utils.LoginUtil;
import com.shanghaionstar.utils.MapHandler;
import com.shanghaionstar.utils.ViewUitl;

import java.util.List;
import java.util.Map;

import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by 6335yz on 2016/7/7.
 */
public class NavMainFragment extends BaseFragment implements INavMainView, ILoginListener, ILoginAndOutListener {
    @FindViewById
    private ScrollView scrollview;
    private String[] titles;
    @FindViewById
    private TabLayout tablayout;
    private NavMainPresenter navMainPresenter;
    @FindViewById
    private GridView gridView_search_view;

    private TabLayout.Tab tab_history, tab_fav;

    @FindViewById
    private ViewPager view_pager;

    @FindViewById
    RelativeLayout my_foot_print;

    /**
     * 记录收藏历史viewpager 手指移动
     */
    private float mLastX;
    @FindViewById
    private View my_locate, vehicle_locate;

    private FragmentManager fragmentManager;

    private AbstractMapActivity mapActivity;
    @FindViewById
    private CustomImageView right_btn;

    @FindViewById
    private DeleteEditText edit_search_addressinfo;
    @FindViewById
    private ListView search_listview;
    ProgressDialog progDialog;

    private MapHandler mapHandler;
    private NavPoiSearchListAdapter navPoiSearchListAdapter;
    private int lastItemIndex = 0;
    private boolean isNextPage = false;
    private String[] gridViewTextInfos;
    private int[] gridViewImages;

    @FindViewById(R.id.radio_group_view)
    private RadioGroup radio_group_view;
    @FindViewById(R.id.rbtn_history)
    private RadioButton rbtn_history;
    @FindViewById(R.id.rbtn_collect)
    private RadioButton rbtn_collect;

    @FindViewById
    private Button btn_clean_seekinfo;
//    @FindViewById(R.id.package_list_progress)
//    private ProgressLayout package_list_progress;

    @FindViewById(R.id.list_va)
    private ViewAnimator list_va;
    private NavPoiSearchHistoryAdapter historyAdapter;

    //    private NavSearchHistoryPresenter navSearchHistoryPresenter;
    // 显示历史记录和收藏家数据
    @FindViewById(R.id.listview_history)
    private ListView listview_history;

    @FindViewById(R.id.listview_favorite)
    private ListView listview_favorite;

    @FindViewById(R.id.nav_historyorfavorite_list_data)
    private TextView nav_historyorfavorite_list_data;

    @FindViewById
    private RelativeLayout frame_back;
    @FindViewById
    private View his_layout;
    @FindViewById
    private ProgressLayout loading_progress;
    @FindViewById
    private CustomImageView home_edit, comp_edit;

    @Override
    public int getLayoutId() {
        return R.layout.nav_search;
    }

    private NavPoiSearchFavAdapter navPoiSearchFavAdapter;
    //    private NavSearchFavSimpleListPresenter navSearchFavPresenter;
    // 更多下发历史记录
    @FindViewById(R.id.btn_bottom_more_history_record)
    private CustomBtnDrawableRightCenter btn_bottom_more_history_record;
    @FindViewById
    private View fav_layout;
    @FindViewById
    private TextView edit_set_gohomeinfo, edit_set_gocompanyinfo;

    @Override
    public Activity onActivity() {
        return mapActivity;
    }

    private LoginUtil mLoginUtil;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        titles = getResources().getStringArray(R.array.nav_fav_his);
        navMainPresenter = new NavMainPresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
        navMainPresenter.setView(this);
        initGridViewData();
        progDialog = new ProgressDialog(mapActivity);
        pinCallBack();
        initEditText();
        initHistoryFav();
        initBack();
        mLoginUtil = new LoginUtil();
        mLoginUtil.loginAndOutShowView(mapActivity, this);
        initShortCutCommand();
    }

    private Subscription navMainPageSubscription;

    public void pinCallBack() {
        /**
         * 从pin码页面返回
         */
        navMainPageSubscription = RxBus.getDefault().toObserverable(RxConstants.NAV_MAIN_PAGE, PinModel.class).filter(new Func1<PinModel, Boolean>() {
            @Override
            public Boolean call(PinModel pinModel) {
                return pinModel.isPinSuccess();
            }
        }).subscribeOn(new AppScheduler().backgroundThread())
                .observeOn(new AppScheduler().mainThread()).subscribe(new Action1<PinModel>() {
                    @Override
                    public void call(PinModel pinModel) {
                        if (pinModel.isPinSuccess()) {
                            if (navMainPresenter == null) {
                                navMainPresenter = new NavMainPresenter(mapActivity.getScheduler(), mapActivity, mapHandler);
                                navMainPresenter.setView(NavMainFragment.this);
                            }
                            navMainPresenter.getVehicleLocation();
                        }
                    }
                });
    }

    /***
     * 高德地图发送到车poi  分割线
     ***/
    Bundle poiItemInfoBundle;

    public void setArgument(Bundle bundle) {
        this.poiItemInfoBundle = bundle;
    }

    private void sendAmapPoiToCar() {
        log.d("sendAmapPoiToCar...");
        if (poiItemInfoBundle != null) {
            SharedPoiItemInfo poiItemInfo = (SharedPoiItemInfo) poiItemInfoBundle.getSerializable(Constants.PARTNER_3RD_POI);
            if (poiItemInfo != null) {
                log.d("sendAmapPoiToCar...poiItemInfo != null");
                if (poiItemInfo.isAutoSendTBT())
                    historyAdapter.sendToCar(poiItemInfo);
                else
                    mapActivity.showPoiToMap(poiItemInfo, LocationType.POI);
            }
            poiItemInfoBundle = null;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //发送高德poi到车
        sendAmapPoiToCar();
    }

    /***
     * 高德地图发送到车poi  分割线
     ***/

    private void initBack() {
        frame_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /**
                 * 这里navmapfragment在栈底
                 */
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_Return.getStringValue());
//                mapActivity.removeUntilFragment(fragmentManager, NavMapFragment.class, true);
                mapActivity.finish();
            }
        });
    }


    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mapActivity = (AbstractMapActivity) activity;
        fragmentManager = mapActivity.getSupportFragmentManager();
        mapHandler = mapActivity.getMapHandler();
    }

    /**
     * @Title: initGridViewData
     * @Description: 初始化Gridview的数据
     */
    public void initGridViewData() {
        TypedArray ar = getResources().obtainTypedArray(R.array.gridItem_image);
        int len = ar.length();
        gridViewImages = new int[len];
        for (int i = 0; i < len; i++) {
            gridViewImages[i] = ar.getResourceId(i, 0);
        }
        ar.recycle();
        gridViewTextInfos = getResources().getStringArray(R.array.griditem_info);
        navMainPresenter.loadSearchItem(gridViewImages, gridViewTextInfos);
    }

    /**
     * 显示gridview数据
     *
     * @param datas
     */
    @Override
    public void showSearchItem(final List<Map<String, Object>> datas) {
        NavSearchItemGridViewAdapter adapter = new NavSearchItemGridViewAdapter(datas, mapActivity);
        gridView_search_view.setAdapter(adapter);
        gridView_search_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mapActivity.hideSoftInput();
                edit_search_addressinfo.setText("");
//                view.getTag();
                navMainPresenter.onGridViewItemClick(position, gridViewTextInfos, parent.getChildAt(position).findViewById(R.id.grid_image));
            }
        });
    }

    public void initHistoryFav() {
        radio_group_view.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                mapActivity.hideSoftInput();
                switch (checkedId) {
                    case R.id.rbtn_history:// 历史记录
                        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_History.getStringValue());
                        navMainPresenter.getHistoryData();
                        list_va.setDisplayedChild(0);
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                list_va.setMeasureAllChildren(false);
                                list_va.invalidate();
                            }
                        });
                        break;
                    case R.id.rbtn_collect:// 收藏夹
                        BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_Favorite.getStringValue());
                        Bundle bundle = new Bundle();
                        bundle.putInt("id", R.id.rbtn_collect);
                        new LoginUtil().loginAndActionCallBack(mapActivity, RxConstants.ACTION_NAV_FAV, NavMainFragment.this, bundle);
                        if (!ApplicationUtil.getInstance().isLogin()) {
                            radio_group_view.check(R.id.rbtn_history);
                        }
                        break;
                }
            }
        });
        /**
         * 默认选中第一项
         */
        radio_group_view.check(R.id.rbtn_history);

    }

    @Override
    public void setLoading(boolean isLoading) {
    }

    @Override
    public void showMapLoading(boolean isShow, String msg) {
        if (progDialog != null) {
            if (isShow) {
                if (!progDialog.isShowing()) {
                    progDialog.setTitle(getString(R.string.waiting));
                    progDialog.setMessage(msg);
                    progDialog.show();
                }
            } else {
                if (progDialog.isShowing()) {
                    progDialog.dismiss();
                }
            }
        }
    }

    @Override
    public void onResponseError(OnStarException e) {
        if (getString(R.string.opt_out_alert).equalsIgnoreCase(e.getMessage())) {
            AlertDialogUtil.showAlertDialog(mapActivity, getString(R.string.dialog_warning),
                    mapActivity.getString(R.string.opt_out_alert));
        } else {
            AlertDialogUtil.showDialogByOnstarException(onActivity(), e);
        }
    }

    @Override
    public void onReponseSuccess(NavInfoModel navInfoModel) {
    }

    @OnClick({R.id.my_foot_print, R.id.my_locate, R.id.vehicle_locate,
            R.id.right_btn, R.id.btn_clean_seekinfo, R.id.btn_bottom_more_history_record,
            R.id.home_edit, R.id.comp_edit, R.id.edit_set_gocompanyinfo, R.id.edit_set_gohomeinfo})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.edit_set_gocompanyinfo:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_OfficeAddressEdit.getStringValue());
                navMainPresenter.showHomeCompPoi(String.valueOf(edit_set_gocompanyinfo.getText()), MapChoosePoiType.COMPANY);
                break;
            case R.id.edit_set_gohomeinfo:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_HomeAddressEdit.getStringValue());
                navMainPresenter.showHomeCompPoi(String.valueOf(edit_set_gohomeinfo.getText()), MapChoosePoiType.HOME);
                break;
            case R.id.my_foot_print:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_MyFootprint.getStringValue());
                Bundle foot = new Bundle();
                foot.putInt("id", R.id.my_foot_print);
                new LoginUtil().loginAndActionCallBack(mapActivity, RxConstants.ACTION_NAV_FAV, NavMainFragment.this, foot);
                break;
            case R.id.my_locate:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_MyPosition.getStringValue());
//                mapActivity.showFragment(fragmentManager, NavMapFragment.class, getClass());
                mapActivity.showPoiToMap(mapActivity.getNavDataHolder().getMyPoi(), LocationType.MYSELF);
                break;
            case R.id.right_btn:
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_SearchPOI.getStringValue());
                mapActivity.hideSoftInput();
                navMainPresenter.search(String.valueOf(edit_search_addressinfo.getText()));
                break;
            case R.id.vehicle_locate:
                //test
//                PollingResult pollingResult = new PollingResult();
//                pollingResult.setLat("31.26626");
//                pollingResult.setLon("121.39729");
//                pollingResult.setRequestType(RemoteCommandsType.COMMANDS_LOCATION.value());
//                RxBus.getDefault().post(RxConstants.ALL_PAGE_ALERT, pollingResult);
                BusinessUtil.sendReportByClickType(getActivity(), FunctionNameFindId.Mytrip_Locator.getStringValue());
                Bundle vehicle = new Bundle();
                vehicle.putInt("id", R.id.vehicle_locate);
                new LoginUtil().loginAndActionCallBack(mapActivity, RxConstants.ACTION_NAV_FAV, NavMainFragment.this, vehicle);
                break;
            case R.id.btn_clean_seekinfo:
                BusinessUtil.sendReportByClickType(mapActivity,
                        FunctionNameFindId.Mytrip_ClearHistory.getStringValue());
                navMainPresenter.clearHistory();
                break;
            case R.id.btn_bottom_more_history_record:// 更多下发历史记录
                BusinessUtil.sendReportByClickType(mapActivity,
                        FunctionNameFindId.Mytrip_NavigationHistory.getStringValue());
                Bundle bundle = new Bundle();
                bundle.putInt("id", R.id.btn_bottom_more_history_record);
                new LoginUtil().loginAndActionCallBack(mapActivity, RxConstants.ACTION_NAV_FAV, NavMainFragment.this, bundle);
                break;
            case R.id.home_edit:
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Clickhomefield.getStringValue());
                if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
                    return;
                }
//                NavSetAddressFragment navSetAddressFragment = NavSetAddressFragment.newInstance(MapChoosePoiType.HOME);
//                NavChoosePointInMapFragment navChoosePointInMapFragment = NavChoosePointInMapFragment.newInstance(MapChoosePoiType.HOME);
//                mapActivity.addFragment(fragmentManager, navChoosePointInMapFragment, true);
//                mapActivity.addFragment(fragmentManager, navSetAddressFragment, true);
//                mapActivity.showFragment(fragmentManager, NavSetAddressFragment.class, NavMainFragment.class);
                Intent intent = new Intent(mapActivity, NavChooseInMapActivity.class);
                intent.putExtra("mapChoosePoiType",MapChoosePoiType.HOME);
                mapActivity.startActivityForResult(intent,1);
                break;
            case R.id.comp_edit:
                BusinessUtil.sendReportByClickType(mapActivity, FunctionNameFindId.Clickofficefield.getStringValue());
                if (!BusinessUtil.checkDriverOrProxyAndShowDialog(mapActivity)) {
                    return;
                }
//                NavSetAddressFragment comp = NavSetAddressFragment.newInstance(MapChoosePoiType.COMPANY);
//                NavChoosePointInMapFragment compMap = NavChoosePointInMapFragment.newInstance(MapChoosePoiType.COMPANY);
//                mapActivity.addFragment(fragmentManager, compMap, true);
//                mapActivity.addFragment(fragmentManager, comp, true);
//                mapActivity.showFragment(fragmentManager, NavSetAddressFragment.class, NavMainFragment.class);
                Intent intent2 = new Intent(mapActivity, NavChooseInMapActivity.class);
                intent2.putExtra("mapChoosePoiType",MapChoosePoiType.COMPANY);
                mapActivity.startActivityForResult(intent2,1);
                break;
        }
    }

    /**
     * 搜索结果回调
     *
     * @param searchPoiList
     */
    @Override
    public void showSearchResult(final List<PoiItemInfo> searchPoiList) {
        mapActivity.hideSoftInput();
        if (searchPoiList != null && searchPoiList.size() > 0) {
            scrollview.setVisibility(View.GONE);
        }
        search_listview.setVisibility(View.VISIBLE);
        isNextPage = mapHandler.IfhasNextPage();
        if (navPoiSearchListAdapter == null) {
            navPoiSearchListAdapter = new NavPoiSearchListAdapter(searchPoiList, mapActivity, false, -1);
            search_listview.setAdapter(navPoiSearchListAdapter);
            search_listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if (searchPoiList != null) {
                        navMainPresenter.showPoiToMap(searchPoiList.get(position), LocationType.POI);
                    }
                    navMainPresenter.getHistoryData();
                }
            });
            search_listview.setOnScrollListener(new AbsListView.OnScrollListener() {
                @Override
                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                    lastItemIndex = firstVisibleItem + visibleItemCount;
                }

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {
                    if (!isNextPage) {
                        return;
                    }
                    if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                            && lastItemIndex == navPoiSearchListAdapter.getCount()) {
                        try {
                            mapHandler.nextPageResult();
                            isNextPage = false;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            });
        } else {
            navPoiSearchListAdapter.setmItemList(searchPoiList);
            navPoiSearchListAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void showSearchResultWithNodata() {
        edit_search_addressinfo.clearAll();
        search_listview.setVisibility(View.GONE);
        AlertDialogUtil.showAlertDialog(mapActivity, getString(R.string.dialog_warning), getString(R.string.poi_no_search));
    }

    /**
     * 当切出当前页面，清除搜索结果列表
     *
     * @param hidden
     */
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (mapHandler != null && navMainPresenter != null && !hidden){
            mapHandler.registOnMapSearchCallBack(navMainPresenter);
        }
        search_listview.setVisibility(View.VISIBLE);
        /**
         * 显示当前搜索主页，在显示搜索结果列表时候隐藏
         */
        scrollview.setVisibility(View.VISIBLE);
        clearPoiSearchInput();
//        if (!hidden) {
//            if (view_pager != null) {
//                view_pager.setCurrentItem(0);
//            }
//            NavDataHolder dataHolder = mapActivity.getNavDataHolder();
//            if (dataHolder != null) {
//                dataHolder.getMapHomeChoosePoi();
//                if (dataHolder.getMapHomeChoosePoi() != null) {
//                    edit_set_gohomeinfo.setText(dataHolder.getMapHomeChoosePoi().getTitle());
//                }
//                if (dataHolder.getMapCompChoosePoi() != null) {
//                    edit_set_gocompanyinfo.setText(dataHolder.getMapCompChoosePoi().getTitle());
//                }
//            }
//        }
    }


    private void initEditText() {
        edit_search_addressinfo.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    navMainPresenter.search(String.valueOf(edit_search_addressinfo.getText()));
                    return true;
                }
                return false;
            }
        });

        edit_search_addressinfo.setOnTextChangeListener(new DeleteEditText.OnTextChangeListener() {
            @Override
            public void textChangeListener(View view, CharSequence text) {
                if (CommonUtil.isNull(text.toString())) {
                    right_btn.setVisibility(View.INVISIBLE);
                    right_btn.setClickable(false);
                    right_btn.setEnabled(false);
                } else {
                    right_btn.setVisibility(View.VISIBLE);
                    right_btn.setClickable(true);
                    right_btn.setEnabled(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (CommonUtil.isNull(edit_search_addressinfo.getText().toString().trim())) {
                    search_listview.setVisibility(View.GONE);
                    edit_search_addressinfo.clearFocus();
                }
            }
        });
    }

    @Override
    public void showHis(boolean isShow) {
        if (isShow) {
            favLoading(false);
            his_layout.setVisibility(View.VISIBLE);
            fav_layout.setVisibility(View.GONE);
        } else {
            favLoading(true);
            his_layout.setVisibility(View.GONE);
            fav_layout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hisHasData(boolean hasData) {
        if (hasData) {
            btn_clean_seekinfo.setVisibility(View.VISIBLE);
            btn_bottom_more_history_record.setVisibility(View.VISIBLE);
            nav_historyorfavorite_list_data.setVisibility(View.GONE);
        } else {
            btn_clean_seekinfo.setVisibility(View.GONE);
            btn_bottom_more_history_record.setVisibility(View.GONE);
            nav_historyorfavorite_list_data.setVisibility(View.VISIBLE);
            nav_historyorfavorite_list_data.setText(mapActivity.getString(R.string.nav_no_history_data));

        }
    }

    @Override
    public void favLoading(boolean isLoading) {
        if (isLoading) {
            loading_progress.setVisibility(View.VISIBLE);
        } else {
            loading_progress.setVisibility(View.GONE);
        }
    }

    @Override
    public void clearPoiSearchInput() {
        edit_search_addressinfo.clearAll();
    }

    @Override
    public void showDeleteDialog(final PoiItemInfo poiItemInfo, final int position) {
        Dialog commonDialog;
        AlertDialog.Builder b = new AlertDialog.Builder(mapActivity);
        b.setMessage(getString(R.string.delete_favorite));
        b.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        b.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                navMainPresenter.deleteFavoriteDestination(poiItemInfo, position);
            }
        });
        commonDialog = b.create();
        commonDialog.setCancelable(true);
        commonDialog.show();
    }

    @Override
    public void showSearchFav(List<FavoriteEntity> list) {
        if (navPoiSearchFavAdapter == null) {
            navPoiSearchFavAdapter = new NavPoiSearchFavAdapter(list, mapActivity, navMainPresenter);
            listview_favorite.setAdapter(navPoiSearchFavAdapter);
        } else {
            navPoiSearchFavAdapter.setList(list);
            navPoiSearchFavAdapter.notifyDataSetChanged();
        }
        //根据listview中的item数量控制其listview的显示高度
        int listViewHeight = ViewUitl.setListViewHeightBasedOnChildren(mapActivity, listview_favorite);
        ViewGroup.LayoutParams params = listview_favorite.getLayoutParams();
        if (!CommonUtil.isNull(params)) {
            params.height = listViewHeight;
            listview_favorite.setLayoutParams(params);
        }
    }

    @Override
    public void showSearchHistory(final List<PoiSearchHistory> historyList) {
        mapActivity.hideSoftInput();
        historyAdapter = new NavPoiSearchHistoryAdapter(historyList, mapActivity, navMainPresenter, true);
        listview_history.setAdapter(historyAdapter);
        //根据listview中的item数量控制其listview的显示高度
        int listViewHeight = ViewUitl.setListViewHeightBasedOnChildren(mapActivity, listview_history);
        ViewGroup.LayoutParams params = listview_history.getLayoutParams();
        if (!CommonUtil.isNull(params)) {
            params.height = listViewHeight;
            listview_history.setLayoutParams(params);
        }
        listview_history.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (historyList.get(position) != null) {
                    navMainPresenter.favDataShowInMap(historyList.get(position), LocationType.POI);
                }
            }
        });
    }


    @Override
    public void showHomeCompText(String home, String comp) {
        edit_set_gohomeinfo.setText(home);
        edit_set_gocompanyinfo.setText(comp);

//        edit_set_gohomeinfo.setText("");
//        edit_set_gocompanyinfo.setText("");

    }

    /**
     * 登录登出是界面刷新回调
     */
    @Override
    public void onLogin() {
        if (navMainPresenter != null) {
            if (Constants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
                my_foot_print.setVisibility(View.VISIBLE);
            } else {
                my_foot_print.setVisibility(View.GONE);
            }
            navMainPresenter.initUserAddressInfo();
        }
    }

    /**
     * 登录登出是界面刷新回调
     */
    @Override
    public void onLoginOut() {
        if (navMainPresenter != null) {
            navMainPresenter.initUserAddressInfo();
        }
        my_foot_print.setVisibility(View.VISIBLE);
    }

    /**
     * 点击未登录时回调
     *
     * @param bundle
     * @param resultCode
     */
    @Override
    public void onLogin(Bundle bundle, String resultCode) {
        if (RxConstants.ACTION_SUCCESS.equals(resultCode)) {
            if (bundle != null) {
                int id = bundle.getInt("id");
                switch (id) {
                    case R.id.btn_bottom_more_history_record:
                        mapActivity.addFragment(fragmentManager, new NavMoreIssuedHistoryFragment(), true);
                        mapActivity.showFragment(fragmentManager, NavMoreIssuedHistoryFragment.class, NavMainFragment.class);
                        break;
                    case R.id.rbtn_collect:
                        list_va.setDisplayedChild(1);
                        radio_group_view.check(R.id.rbtn_collect);
                        navMainPresenter.doGetFavList();
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                list_va.setMeasureAllChildren(false);
                                list_va.invalidate();
                            }
                        });
                        break;
                    case R.id.vehicle_locate:
                        navMainPresenter.findVehicleLocation();
                        break;
                    case R.id.my_foot_print:
                        if (Constants.OWNER.equalsIgnoreCase(ApplicationUtil.getInstance().getLoginRole())) {
                            NavMyFootPrintFragment n1 = new NavMyFootPrintFragment();
                            mapActivity.addFragment(fragmentManager, n1, true);
                            mapActivity.showFragment(fragmentManager, NavMyFootPrintFragment.class, NavMainFragment.class);
                        }
                        break;
                }
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (navMainPresenter != null) {
            LogManager.getInstance().d(">>>>-----------------------------NavMainFragment is destroyed --------------------------------------<<<<");
            navMainPresenter.finish();
            navMainPresenter = null;
        }
        if (navMainPageSubscription != null && !navMainPageSubscription.isUnsubscribed()) {
            navMainPageSubscription.unsubscribe();
            navMainPageSubscription = null;
        }
        if(mLoginUtil != null)
            mLoginUtil.clearLoginOrOut();
    }

    @Override
    public void onFragmentBackPress() {
        mapActivity.finish();
    }


    @Override
    public void showCommandLoading(boolean isShow) {
        if (isShow && mapActivity != null) {
            startActivity(new Intent(mapActivity, VehicleLoadingActivity.class));
        }
    }


    /**
     * 发送tbt失败重试toast
     */
    @Override
    public void showAppFrontNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        AlertDialogUtil.showAlertDialog(mapActivity, getString(R.string.dialog_warning), getString(R.string.nav_command_fail_alert), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                navMainPresenter.sendTbtOrOdd(poiItemInfo);
            }
        });
    }

    /**
     * app在后端时候，发送tbt失败提示toast
     *
     * @param poiItemInfo
     */
    @Override
    public void showAppBackNavCommandFailToast(final PoiItemInfo poiItemInfo) {
        ToastView toastView = new ToastView(mapActivity);
        toastView.setToastClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppFrontNavCommandFailToast(poiItemInfo);
            }
        });
    }

    private void initShortCutCommand() {
        if (getArguments() != null) {
            if (getArguments().getSerializable("remoteCommandsType") != null) {
                RemoteCommandsType remoteCommandsType = (RemoteCommandsType) getArguments().getSerializable("remoteCommandsType");
                if (remoteCommandsType == null) return;
                switch (remoteCommandsType) {
                    case COMMANDS_LOCATION:
                        vehicle_locate.performClick();
                        break;
                    case COMMAND_GO_HOME:
                        if (CommonUtil.isNull(edit_set_gohomeinfo.getText())) {
//                            AlertDialogUtil.showAlertDialog(getContext(), R.string.set_go_home_addr,
//                                    new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                     dialog.dismiss();
//                                     home_edit.performClick();
//                                }
//                            }, new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    dialog.dismiss();
//                                }
//                            });
                            home_edit.performClick();
                        } else {
                            if (mapActivity.getNavDataHolder() != null) {
                                navMainPresenter.sendTbtOrOdd(mapActivity.getNavDataHolder().getMapHomeChoosePoi());
                            }
                        }
                        break;
                    case COMMAND_GO_COMPANY:
                        if (CommonUtil.isNull(edit_set_gocompanyinfo.getText())) {
                            comp_edit.performClick();
                        } else {
                            if (mapActivity.getNavDataHolder() != null) {
                                navMainPresenter.sendTbtOrOdd(mapActivity.getNavDataHolder().getMapCompChoosePoi());
                            }
                        }
                        break;
                }
            }
        }
    }

    public static NavMainFragment newInstance(RemoteCommandsType remoteCommandsType) {
        NavMainFragment navMainFragment = new NavMainFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable("remoteCommandsType", remoteCommandsType);
        navMainFragment.setArguments(bundle);
        return navMainFragment;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == 1) {
            Object obj = data.getSerializableExtra("result");
            if(obj instanceof SetAddressResult) {
                SetAddressResult setAddressResult = (SetAddressResult)obj;
                if(setAddressResult.mapChoosePoiType == MapChoosePoiType.HOME) {
                    edit_set_gohomeinfo.setText(setAddressResult.poiItemInfo.getTitle());
                }
                if (setAddressResult.mapChoosePoiType == MapChoosePoiType.COMPANY) {
                    edit_set_gocompanyinfo.setText(setAddressResult.poiItemInfo.getTitle());
                }
            }
        }
    }
}
